###############################
### Quick Thematic Map      ###
###############################
rm(list = ls())

# fix input string errors
Sys.setlocale('LC_ALL', 'C')
options(scipen=20)

##create folder structure
mainDir <- "" # insert your path

subDir <- "Replication_Files/Results/graphs/R_out"
if (file.exists(file.path(mainDir, subDir))){
  setwd(file.path(mainDir, subDir))
} else {
  dir.create(file.path(mainDir, subDir))
  setwd(file.path(mainDir, subDir))
}

# required
lop <- c("raster", "sp", "tmap","readstata13", "sf", "doBy", "RColorBrewer","OpenStreetMap", "tmaptools")
newp <- lop[!(lop %in% installed.packages()[,"Package"])]
if(length(newp)) install.packages(newp)
lapply(lop, require, character.only = TRUE)


## zone data
grid.sf <- st_read("../../../Data/country_regions/gadm1_clean.shp")


### get sf object for entire African countries
africa_countries <- st_read("../../../Data/country_regions/gadm28_adm0.shp")
africa_countries <- subset(africa_countries, UNREGION2=="Africa")
# manually set Reunion as Island
africa_countries[which((africa_countries$NAME_ENGLI=="Reunion")), which(names(africa_countries)=="Islands")] <- 1 
africa_countries <- subset(africa_countries, Islands==0)
#add Madagscar and Mauritius to sample despite being islands
isos <- c(as.character(unique(africa_countries$ISO)), "MDG", "MUS")
africa_countries$ISO <- as.character(africa_countries$ISO)

## Get sf data
gadm1_africa <- grid.sf %>% 
  subset(., ISO%in%isos) 
gadm1_africa$ISO <- as.character(gadm1_africa$ISO)

## data
ged.csv <- read.csv("../../../Data/UCDP-GED/ged50.csv", stringsAsFactors = F)

ged_cleaned <- subset(ged.csv, where_prec<=4)
ged_cleaned <- subset(ged_cleaned, region=="Africa")
ged_cleaned <- subset(ged_cleaned, year>=1996 & year <=2014)
ged_cleaned.sf <- st_as_sf(ged_cleaned, coords = c("longitude", "latitude"))

BRD4 <- subset(ged_cleaned.sf, best_est<5)
BRD24 <- subset(ged_cleaned.sf, best_est>=5 & best_est<=24)
BRD25more <- subset(ged_cleaned.sf, best_est>25)



palette_name <- "YlOrRd"
legend_colors <- c(get_brewer_pal(palette_name, n=5), "grey")

## set up font family
# install.packages("extrafont")
library(extrafont)
# font_import()
# y
loadfonts()
loadfonts(device="win")

## Create PDF and png
plot_conf_ida <- function(maplayout="esri-topo"){
  ## load basemap data
  # read OSM raster data
  osm_afri <- read_osm(africa_countries, ext=1.1, type=maplayout)
  
  
  
  print (
    tm_shape(osm_afri) +
      tm_rgb() +
      tm_shape(africa_countries)+
      tm_borders(lwd = 2)+
      tm_shape(gadm1_africa) +
      tm_borders(col = "grey40", alpha = 0.4) +
      tm_shape(BRD4) + 
      tm_dots(col="darkorange2"
              , alpha = 1
              , scale=4
              , border.lwd=NA
              , shape=21
      )  +
      tm_shape(BRD24) + 
      tm_dots(col="firebrick3"
              , alpha = 1
              , scale=4
              , border.lwd=0.4
              , border.alpha =0.5
              , shape=22
      )  +
      tm_shape(BRD25more) + 
      tm_dots(col="black"
              , alpha = 1
              , scale=4
              , shape=25
              , border.alpha =0.5
      )  +
      tm_add_legend(type = "symbol"
                    , shape = c(21,22,25)
                    , size=c(1.1,1.1,1)
                    , col = c("darkorange2", "firebrick3", "black")
                    , title = "Battle-Related Deaths"
                    , labels = c("A: less than 5", "B: Between 5 and 25", "C: More than 25")) +
      tm_scale_bar(size = 1
                   , width = 0.2)+
      tm_layout(legend.position = c("left", "bottom")
                , legend.text.size = 1.4
                , legend.title.size = 1.9
                , legend.width=0.9
                , fontfamily = "Helvetica"
                , frame = F #put frame around graph?
                , legend.outside = F # legend outside of margin?
                , outer.margins = c(0, 0, 0, 0) # Relative margins between device and frame (bottom, left, top, right)
      ) 
  )
}

png(paste0("map_conflict_only_test3.png"))
plot_conf_ida(maplayout="nps")
dev.off()

## pdf format
# pdf(paste0("map_conflict_only.pdf"), width=8, height=8)
# par(mfrow=c(1,1))
# par(mar = c(0,0,0,0)) # c(bottom, left, top, right)
# plot_conf_ida(maplayout="nps")
# dev.off()

## esp format
# setEPS()
# postscript("map_conflict_only.eps")
# plot_conf_ida()
# dev.off()




